/**
 * 发起表单
*/
import jQuery from "jquery";
import { useForm } from "../../framework/common/context/metadata-context";
import { Tooltip, Button ,Input,Form, Col, Row, Select, Checkbox} from 'antd';
import axios from "axios";
import { useEffect, useRef, useState } from "react";
import clsx from "clsx";
import SelectAuditors from "../../RuntimeForm/SelectAuditors/SelectAuditors.js";
import Sign from "../../RuntimeForm/Sign1/Sign1";/*签章组件 */
import getApproveOptions from "./getApproveOptions.js";//获取按钮对应信息
import getInitiateFormData from '../../framework/common/utils/getInitiateFormData';//获取流程表单数据
import "./initiateForm.css";
import md5 from "js-md5";
import message from "../../framework/common/utils/message";
import request from "../../framework/common/utils/request";
import cloneDeep from 'lodash/cloneDeep'
import { InjectProvider } from "../../framework/common/context/inject-context";
import { initAllStepData } from "../../RuntimeForm/ApproveStep/stepUtility";/*审批步骤数据清洗*/
import ModalStepEdit from "../../RuntimeForm/ApproveStep/ModalStepEdit1";/*弹出可编辑流程图*/
import eventBus, { useSubscribe } from "../../framework/common/eventBus";

import InitiaterOrg from "./components/InitiaterOrg";//发起组织
import { formDataReload } from "../Header/businessBtnUtils";
import { showInitiateSteps, beforeApproeValidate } from "./submitApproveForm";//发起审批
import { dblClick } from "@testing-library/user-event/dist/click";

const { TextArea } = Input;
const { Option } = Select;


export default function ({toggleFooter,hideFooter, approveType }) {
    const metadataManager = useForm().root;
    const { data: tplData, urlPrefix, params, getErrors} = metadataManager;
    const [form] = Form.useForm();//表单对象
    tplData.__approveType__ = approveType;//进入发起表单时，打上当前审批状态标记

    //发起组织change
    function orgIdChange(option){
        if(option.value){
            //组织切换时，更改监控人
            request({
                url: '/flowinstance/process/check-monitor',
                data:{
                    flow_id: params.flow_id,
                    flow_templeta_id: params.flow_template_id,
                    org_id: option.value,
                    monitor: tplData.ProcessInfo.Monitors
                },
                method: 'POST'
            }).then(function(result){
                if(result.code == 1){
                    if(result.data){
                        tplData.ProcessInfo.newMonitors = result.data;//更新监控人
                        eventBus.publish("monitor.update");//更新监控人
                    }
                }
            });
        }else{
            tplData.ProcessInfo.newMonitors = [];//更新监控人
            eventBus.publish("monitor.update");//更新监控人
        }

        eventBus.publish("refreshTitle.update");//更新标题//refreshTitle();
        
        if (tplData.ApproveDepartRole.ReLoadCcData && tplData.ApproveDepartRole.ReLoadCcData == 1) {
            var DepartRole = option.value;
            if (!DepartRole) {
                return;
            }

            if (tplData.form.FormMode == 1) {//发送消息 老表单需要发送消息
                //todo 兼容老表单
                // var component = getFormComponent();
                // component.sendMessageForGetFormData({
                //     isDraft: false,
                //     sendType: 2,
                //     isApproveBtn: false
                // });
            } 
        }
    }
    
    //发起人change-代理发起人change事件
    const agentChange = (data)=>{
        var auditor = data[0];
        if(auditor){
            //联动改变代理发起人信息
            let agentInitiaterData = {
                initiater_id: auditor.auditor_id,//联动改变发起部门信息
                initiater_name: auditor.auditor_name,//联动改变发起部门信息
            }
            form.setFieldsValue(agentInitiaterData);//更新表单数据
            updateTplData(agentInitiaterData);//更新tplData
            request({
                url: "/organization/ou/get-user-by-code?filter_disable=1",
                //isForm: true,
                method: "get",
                data:{
                    code: auditor.auditor_code
                },
                noTip: true
            }).then(
                function (result) {
                    var data = result.data;
                    if(data.data){
                        var dep = data.data[0].org_settings;
                        eventBus.publish("orgOptionList.update", dep);//更新发起组织数据
                        dep.forEach(function(item, i){
                            if(item.is_default===1 || item.is_default==="1" ){
                                let initiater_org_id = {
                                    initiater_org_id: item.org_id,
                                    initiater_org_name: item.name_path,
                                }
                                form.setFieldsValue(initiater_org_id);//联动改变发起部门信息
                                updateTplData(initiater_org_id);//更新tplData
                                
                                orgIdChange({
                                    value: item.org_id,
                                    children: item.name_path
                                })
                            }
                        });

                        //refreshTitle();//todo
                    }
                },
                function(error){
                
                }
            )
        }else{
            eventBus.publish("orgOptionList.update", []);//更新发起组织数据
            let initiater_data = {
                //联动改变发起部门信息
                initiater_org_id: "",
                initiater_org_name: "",

                //联动改变代理发起人信息
                initiater_id: "",
                initiater_name: "",
            }
            form.setFieldsValue(initiater_data);
            updateTplData(initiater_data);//更新tplData

            orgIdChange({
                value: "",
                children: ""
            })
            //refreshTitle();//todo
        };
    }

    //表单默认值
    if(!tplData.__approveForm__){
        tplData.__approveForm__ = {
            Initiate:{
                opinion:'',//审批意见
                initiater_org_id:'',//发起组织id
                initiater_org_name:'',//发起组织中文名
                process_level: tplData.ProcessInfo?.ProcessLevel == 1 ? true : false,//加急
                step_cc_list: [],//抄送人
                sign_id: tplData.ProfileSign?.default_sign?.id //签章
            }
            //新表单reloadForm后抄送人重新设置数据//todo
            // $(window).on("reloadForm", function () {
            //     tplData.components.selectAuditors.reloadData();
            // });
        }
        if(tplData.ProcessInfo.CanAgent == 1){//当前为代理发起流程
            let selectAgentDefaultValue = [];
            if(tplData?.NodeInfo?.auditor_id){//当前节点包含了代理人信息
                selectAgentDefaultValue = [{
                    'auditor_id': tplData.NodeInfo.auditor_id,
                    'auditor_name': tplData.NodeInfo.auditor_name,
                    'name': tplData.NodeInfo.auditor_name
                }]
            }
            tplData.__approveForm__.Initiate = {
                ...tplData.__approveForm__.Initiate,
                ...{
                    selectAgent: selectAgentDefaultValue,//代理人
                    initiater_id: selectAgentDefaultValue.length ? selectAgentDefaultValue[0].auditor_id : "",//发起人id
                    initiater_name: selectAgentDefaultValue.length ? selectAgentDefaultValue[0].auditor_name : ""//发起人部门
                }
            }//给发起表单追加代理人信息
        }
    }

    //设置发起表单数据，用于ant表单更新后，反向更新tplData内发起表单的数据
    function updateTplData(data) {
        tplData.__approveForm__[approveType] = {
            ...tplData.__approveForm__[approveType],
            ...data,
        };
    }
    
    //返回审批要点内容
    function getApprovePoint(text){
        if(!text){
            return "暂无审批要点"
        }else{
            return <div dangerouslySetInnerHTML={{ __html: text.replace(/\n/g, '<br>') }}></div>
        }
    }

    useEffect(function(){
        //获取默认审批意见
        getApproveOptions(approveType, tplData, params).then(function(result){
            if (result.code == 1) {
                if (result.data) {
                    form.setFieldsValue({
                        opinion: result.data.DefaultOption
                    });//更新表单发起意见
                    updateTplData({
                        opinion: result.data.DefaultOption
                    });//更新tplData
                    let allValues = form.getFieldsValue(true);
                    setInitiateFormData(allValues);//更新tplData
                }
            }
        });

    }, []);

    const [autoApprove, setAutoApprove] = useState(false);//记录自动发起状态，只能自动发起一次
    //设置发起表单数据，用于ant表单更新后，反向更新tplData内发起表单的数据
    function setInitiateFormData(allValues){
        tplData.__approveForm__.Initiate = {...tplData.__approveForm__.Initiate, ...allValues};
        tplData.__approveForm__.Initiate.process_level = allValues.process_level === true ? 1 : 0;//加急单独做一下转换
        if(tplData.ISClickInitiate == 1){//ISClickInitiate为1表示业务系统发起流程需要自动弹出确认路径
            if(!autoApprove){//判断自动发起的状态，只能自动发起一次
                if(window.initiateTimer){
                    clearTimeout(window.initiateTimer);
                }
                //自动发起
                window.initiateTimer = setTimeout(function(){
                    beforeApproeValidate({
                        form: form,
                        metadataManager: metadataManager,
                        tplData: tplData,
                        approveType: approveType,
                        validateSuccess:function(){//校验通过回调
                            showStepPathModel({
                                tplData: tplData,
                                params: params,
                                metadataManager: metadataManager,
                                urlPrefix: urlPrefix,
                                approveType: approveType,
                                setEditModelInfo: setEditModelInfo,
                                setApproveBtnStatue: setApproveBtnStatue
                            });//1、同步业务数据 2、获取发起步骤路径 3、显示确认步骤路径弹出框
                        }
                    });
                    setAutoApprove(true);//更新自动发起状态，true后，就不能再自动发起，因为每次表达change都会触发这里的方法
                },500);//加定时器是为了兼容默认意见和组织信息请求请求都结束后，才做自动发起
            }
        }
    }

    const [editModelInfo, setEditModelInfo] = useState({
        showStepEditModal: false
    })
    const [approveBtnStatue, setApproveBtnStatue] = useState(false);//发起按钮loading状态
    
    return (
        <Form
            form={form}
            name="basic"
            labelAlign={"left"}
            colon={false}
            labelCol={{
                flex: "80px",
            }}
            onValuesChange={(value,allValues)=>{
                //收集发起表单数据，发起组织在onChange事件内
                setInitiateFormData(allValues);
            }}
            initialValues={tplData.__approveForm__.Initiate}
            autoComplete="off">
                <div id="footer" className={clsx("absolute left-0 right-0 bottom-0 bg-white z-[2]", hideFooter && "hideFooter")}>
                    <div className="relative z-10 transition-all duration-300 foot_opt_wrap">
                        <div className="border-t border-gray-998 divide-solid">
                            <Row className="pb-2 mt-4 ml-auto mr-auto w-1100px">
                                <Col span={12} className="pr-4">
                                    <p className="mb-10px">发起意见</p>
                                    <Form.Item
                                        label=""
                                        name="opinion"
                                        rules={[
                                            {
                                                required: true,
                                                message: '',
                                            }
                                        ]}
                                    >
                                        <TextArea showCount={true} rows="4" maxLength="1000" placeholder="请输入发起意见"></TextArea>
                                    </Form.Item>
                                </Col>
                                <Col span={12} className="pl-4">
                                    <Row>
                                        {
                                            tplData.ProcessInfo.CanAgent == 1
                                            && <Col span={10}>
                                                <Form.Item
                                                    className="mb-10px"
                                                    label="发起人"
                                                    name="selectAgent"
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: ''
                                                        }
                                                    ]}
                                                >
                                                    <SelectAuditors
                                                        CurUserGUID={tplData.CurUserGUID} 
                                                        package_id={tplData.package_id}
                                                        CurUserDepartmentGUID={tplData.CurUserDepartmentGUID} 
                                                        urlPrefix={urlPrefix}
                                                        multiSelect={false}
                                                        selectSelf={tplData.ProcessInfo.CanAccess == 1}
                                                        valueField={"auditor_id"}
                                                        onChange={agentChange}
                                                        title={"发起人"}
                                                    ></SelectAuditors>
                                                </Form.Item>
                                            </Col>
                                        }
                                        <Col
                                            className={tplData.ProcessInfo.CanAgent == 1 ? "pl-3 pl-" : ""}
                                            span={tplData.ProcessInfo.CanAgent == 1 ? 14 : 24}>
                                            <Form.Item
                                                className="mb-10px"
                                                label="发起组织"
                                                name="initiater_org_id"
                                                rules={[
                                                    {
                                                        required: true,
                                                        message: '',
                                                    },
                                                ]}
                                            >
                                                <InitiaterOrg
                                                    approveType={approveType}
                                                    setFormData={setInitiateFormData}
                                                    form={form}
                                                    updateTplData={updateTplData}
                                                />
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    {
                                        tplData.show_step_cc === true
                                        && <Form.Item
                                                className="mb-10px"
                                                label="抄送人"
                                                name="step_cc_list"
                                            >
                                                <SelectAuditors
                                                    CurUserGUID={tplData.CurUserGUID} 
                                                    package_id={tplData.package_id}
                                                    CurUserDepartmentGUID={tplData.CurUserDepartmentGUID} 
                                                    urlPrefix={urlPrefix} 
                                                    title={"抄送人"}
                                                    maxTagCount="responsive"
                                                ></SelectAuditors>
                                            </Form.Item>
                                    }
                                    <Form.Item
                                        className="mb-10px"
                                        label="是否加急"
                                        name="process_level"
                                        valuePropName="checked"
                                    >
                                        <Checkbox></Checkbox>
                                    </Form.Item>
                                    {
                                        (tplData.ProfileSign?.enable_sign == 1)
                                        && <Form.Item
                                            className="mb-0"
                                            label="选择签章"
                                            name="sign_id"
                                            rules={[
                                                {
                                                    required: true,
                                                    message: '',
                                                }
                                            ]}
                                        >
                                            <Sign 
                                                CurUserGUID={tplData.CurUserGUID}
                                                package_id={tplData.package_id}
                                                singUrl={tplData.ProfileSign?.default_sign?.image}
                                            ></Sign>
                                        </Form.Item>
                                    }
                                </Col>
                            </Row>
                        </div>
                    </div>
                    <div className="relative z-20 bg-white border-t foot_btn_box border-gray-998 divide-solid leading-50px h-50px">
                        <div className="relative ml-auto mr-auto w-1100px">
                            {
                                //发起按钮
                            }
                            <Button 
                                type="primary" 
                                onClick={()=>{
                                    beforeApproeValidate({
                                        form: form,
                                        metadataManager: metadataManager,
                                        tplData: tplData,
                                        validateSuccess:function(){//校验通过回调
                                            showStepPathModel({
                                                tplData: tplData,
                                                params: params,
                                                metadataManager: metadataManager,
                                                urlPrefix: urlPrefix,
                                                approveType: approveType,
                                                setEditModelInfo: setEditModelInfo,
                                                setApproveBtnStatue: setApproveBtnStatue
                                            });//1、同步业务数据 2、获取发起步骤路径 3、显示确认步骤路径弹出框
                                        }
                                    })
                                }} 
                                loading={approveBtnStatue}
                                className="Initiate-submit">
                                    {tplData.flowOperationNameMap?.[0]?.operationName || "提交"}
                            </Button>

                            <Tooltip getPopupContainer={() => document.querySelector("#footer")} 
                                color="white"
                                overlayClassName="mytip approvePoint" 
                                placement="bottomRight" 
                                trigger="click"
                                title={getApprovePoint(tplData.ApprovePoint)}>
                                    <span className="absolute right-0 cursor-pointer text-color-link">审批要点</span>
                            </Tooltip>
                        </div>
                    </div> 
                    
                    <span 
                        className="put_arrow bg-white absolute right-0 -top-[23px] w-9 h-6 text-center border border-gray-998 divide-solid cursor-pointer leading-22px"
                        onClick={()=>{toggleFooter()}}
                        title="收起">
                        <i className={clsx("iconfont  text-22px text-gray-b1",hideFooter?"icon-jiantou-xiangshang":"icon-jiantou1")}></i>
                    </span>
                </div>

                {
                    /*流程图编辑模式*/
                }

                {
                    editModelInfo.showStepEditModal && 
                    <InjectProvider value={{checkList:{}}}>
                        <ModalStepEdit
                            showStepEditModal={editModelInfo.showStepEditModal}
                            actual_steps={editModelInfo.actual_steps}
                            approveSteps={editModelInfo.approveSteps}
                            validateResult={editModelInfo.validateResult}
                            model={"edit"}
                            tplData={tplData} 
                            params={params} 
                            urlPrefix={urlPrefix}
                            approveType={approveType}
                            handleCancel={()=>{
                                eventBus.publish("cancelALlRerquest");//取消获取流程请求
                                setApproveBtnStatue(false);
                                setEditModelInfo({
                                    showStepEditModal: false
                                });//隐藏确认弹出框
                            }}

                            handleApprove={()=>{
                                console.log('弹出框')
                                // initiateApprove({
                                //     steps: steps,
                                //     tplData: tplData,
                                //     params: params,
                                //     urlPrefix: urlPrefix
                                // })//发起流程
                            }}
                        ></ModalStepEdit>
                    </InjectProvider>
                }
            </Form>
    );
}

//发起流程-只弹出确认步骤路径，实际发起在确认步骤弹框的确定按钮实现
function showStepPathModel({
    tplData,
    params,
    metadataManager,
    urlPrefix,
    approveType,
    setEditModelInfo,
    setApproveBtnStatue
}){
    //同步业务数据
    setApproveBtnStatue(true);//发起按钮loading
    formDataReload({
        form: metadataManager,
        tplData: tplData,
        params: params,
        urlPrefix: urlPrefix,
        success:function(){
            // setApproveBtnStatue(false);//发起按钮loading
            showInitiateSteps({
                params: params,
                tplData: tplData,
                approveType: approveType,
                setEditModelInfo: setEditModelInfo,
                beforeAjax:function(){
                    setApproveBtnStatue(true);
                },
                success:function(){
                    setApproveBtnStatue(false);
                },
                error:function(result){
                    setApproveBtnStatue(false);
                    if(result.message === "canceled"){
                        console.log('主动取消')
                    }else{
                        message.info({
                            content: "获取步骤路径失败",
                        });
                    }
                }
            });
        },
        error:function(){
            setApproveBtnStatue(false);//发起按钮loading
        }
    });
}